import React, { memo, useEffect, useState } from "react";
import type { FC, ReactNode } from "react";
import { LinkSongsWrapper } from "./style";
import { useAppDispatch, useAppSelector } from "@/store";
import { feachPlaylistDetailAction } from "../musicLibrary/store";
import { shallowEqual } from "react-redux";
import AreaItemv3 from "@/components/area-itemv3";

interface IProps {
  children?: ReactNode;
}

const LinkSongs: FC<IProps> = () => {
  const limit = 100
  const [offset, setOffset] = useState(0)
  const [currpage, setCurrpage] = useState(1)
  const [isShowSeach, setIsShowSeach] = useState(0)

  const { likedSongPlaylistID, userInfo, allTracks } = useAppSelector((state) => ({
    likedSongPlaylistID: state.login.likedSongPlaylistID,
    userInfo: state.login.userInfo,
    allTracks: state.musicLibrary.allTracks
  }), shallowEqual)

  const dispatch = useAppDispatch()
  useEffect(() => {
    if (likedSongPlaylistID)
      dispatch(feachPlaylistDetailAction({ id: likedSongPlaylistID, limit, offset, currpage }))
  }, [likedSongPlaylistID, limit, offset, currpage])

  const handleUpload = () => {
    setCurrpage(currpage + 1)
    setOffset((offset + 1) * limit)
  }

  const handleSearchKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    console.log(event)
  }
  return <LinkSongsWrapper>
    <div className="headers">
      <div className="link-info">
        <img className="cover-img" src={userInfo.avatarUrl} alt="用户头像" />
        <div className="title">{`${userInfo.nickname}喜欢的音乐`}</div>
      </div>
      <div className="right-search" style={{ overflow: isShowSeach ? "hidden" : "auto" }} onClick={() => setIsShowSeach(1)}>
        <img className="search-icon" src={require("@/assets/img/search.png")} alt="音乐搜索输入框" />
        <input type="text" className="search-ipt" placeholder="搜索歌单音乐" onKeyDown={e => handleSearchKeyDown(e)} style={{ width: !isShowSeach ? 0 : "120px" }} />
      </div>
    </div>
    <div className="continter-links">
      {
        allTracks.map(item => (
          <AreaItemv3 key={item.id} itemData={item} />
        ))
      }
    </div>

    <div className="upload-btn">
      {allTracks.length > 0 && <div className="btn-text" onClick={handleUpload}>加载更多</div>}
    </div>
  </LinkSongsWrapper>;
};

export default memo(LinkSongs);